package cn.alusiaor.commonutil;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Random;

public class ServerPortUtil {
    /**
     * 获取可用端口，范围2000-65535
     *
     * @return
     */
    public static int getAvailablePort() {
        int max = 65535;
        int min = 2000;
        Random random = new Random();
        int port = random.nextInt(max) % (max - min + 1) + min;
        boolean using = NetUtil.isLocalePortUsing(port);
        if (using) {
            return getAvailablePort();
        } else {
            return port;
        }
    }
    /**
     * 获取本机Ip
     *
     * @return
     */
      private static String getHostIp(String defaultIp) {
        Enumeration<NetworkInterface> allNetInterfaces = null;
        try {
            allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            return defaultIp;
        }
        if (allNetInterfaces == null) {
            return defaultIp;
        }
        while (allNetInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = allNetInterfaces.nextElement();
            Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress ip = addresses.nextElement();
                if (ip instanceof Inet4Address
                        && !ip.isLoopbackAddress()
                        && !ip.getHostAddress().contains(":")) {
                    System.out.println("本机的IP = " + ip.getHostAddress());
                    return ip.getHostAddress();
                }
            }
        }
        return defaultIp;
    }
}
